//
//  RoleSelectViewController.m
//  CardWarrior
//
//  Created by Tekka Xie on 12-4-24.
//  Copyright (c) 2012年 Tencent. All rights reserved.
//

#import "RoleSelectViewController.h"
#import "AudioManager.h"
#import "GameDataManager.h"
#import "FontManager.h"
#import "EasyGlyph.h"
#import "StringSlicer.h"

@implementation RoleSelectViewController

@synthesize starBackgroundA;
@synthesize starBackgroundB;
@synthesize winCountText;
@synthesize nameImageView;
@synthesize firstRowSayImageView;
@synthesize secondRowSayImageView;
@synthesize palyerIndicatorImageView;

static const int ROLE_VIEW_COUNT = 7;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 背景动画
    starBackgroundA.frame = CGRectMake(0, 0, 480, 320);
    starBackgroundB.frame = CGRectMake(0, 320, 480, 320);
    [UIView animateWithDuration: 10.0  delay: 0.0
                        options: UIViewAnimationOptionCurveLinear|UIViewAnimationOptionRepeat
                     animations: ^(){
                         starBackgroundA.frame = CGRectMake(0, -320, 320, 480);
                         starBackgroundB.frame = CGRectMake(0, 0, 480, 320);
                     }
                     completion: nil
     ];
    
    // 初始化角色视图
    for (int i = 0; i < 7; i++)
        roleViews[i] = (UIImageView*)[self.view viewWithTag:i+200-3];
    
    roleViewsFrame[0] = CGRectMake(36, 66, 91, 116);
    roleViewsFrame[1] = CGRectMake(81, 57, 105, 133);
    roleViewsFrame[2] = CGRectMake(126, 48, 118, 149);
    roleViewsFrame[3] = CGRectMake(171, 41, 131, 166);
    roleViewsFrame[4] = CGRectMake(229, 48, 118, 149);
    roleViewsFrame[5] = CGRectMake(287, 57, 105, 133);
    roleViewsFrame[6] = CGRectMake(345, 66, 91, 116);
    
    [self setAllRoleView];
    [self resetAllRoleViewFrame];
    [self setCurrentRoleStatus];
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    if (interfaceOrientation == UIInterfaceOrientationLandscapeRight
        || interfaceOrientation == UIInterfaceOrientationLandscapeLeft)
        return YES;
    
    return NO;
}

#pragma mark - touches

static BOOL isAnimate = NO;

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event 
{
    UITouch *touch = [[event allTouches] anyObject];
    //UIImageView *touchView = (UIImageView*)[touch view];
    
    @autoreleasepool {
    
    if (touch.view.tag == 100)
    {
        // 返回
        [self performSegueWithIdentifier:@"SegueToMainViewController" sender:nil];
        [[AudioManager sharedInstance] PlaySFX:@"BackSFX"];
    }
    else if (touch.view.tag == 101)
    {
        // 确定
        if (![self isCurrentRoleAvaiable])
        {
            [[AudioManager sharedInstance] PlaySFX:@"SelectSFX"];
            return ;
        }
        
        GameDataManager* pDataManager = [GameDataManager sharedInstance];
        [pDataManager saveData];
        [[AudioManager sharedInstance] PlaySFX:@"ConfirmSFX"];
        
        if (pDataManager.gameCurrentMode == 2 &&
            pDataManager.whoIsSelecting == 1)
        {
            // 开始guest选择角色
            [UIView animateWithDuration: 0.5  delay: 0.0
                                options: UIViewAnimationOptionCurveEaseOut
                             animations: ^(){
                                 self.view.alpha = 0.0;
                             }
                             completion: ^(BOOL finished){
                                 [UIView animateWithDuration: 0.5  delay: 0.0
                                                     options: UIViewAnimationOptionCurveEaseOut
                                                  animations: ^(){
                                                      self.view.alpha = 1.0;
                                                      [pDataManager setWhoIsSelecting:2];
                                                      [self setAllRoleView];
                                                      [self resetAllRoleViewFrame];
                                                      [self setCurrentRoleStatus];
                                                  }
                                                  completion: ^(BOOL finished){
                                                      [pDataManager setWhoIsSelecting:2];
                                                  }
                                  ];
                             }
            ];
        }
        else
        {
            srand(time(0));
            if (pDataManager.gameCurrentMode == 1)
                pDataManager.guestSelectedRole = rand()%8;
            [self performSegueWithIdentifier:@"SegueToPkViewController" sender:self];
        }
    }
    else if (touch.view.tag == 103 && isAnimate == NO)
    {
        // 左移
        isAnimate = YES;
        
        [UIView animateWithDuration: 0.3  delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut
                        animations: ^(){
                            roleViews[6].alpha = 1.0;
                            roleViews[1].alpha = 0.0;
                            for (int i = 6; i >= 1 ; i--)
                                roleViews[i].frame = roleViews[i-1].frame;
                        }
                        completion: ^(BOOL finished){
                            
                            GameDataManager* pManager = [GameDataManager sharedInstance];
                            
                            if (pManager.whoIsSelecting == 1)
                                [pManager addHostSelectedRole];
                            else
                                [pManager addGuestSelectedRole];
                            
                            [self setAllRoleView];
                            [self resetAllRoleViewFrame];
                            [self setCurrentRoleStatus];
                            
                            isAnimate = NO;
                        }
        ];
        [[AudioManager sharedInstance] PlaySFX:@"SelectSFX"];
    }
    else if (touch.view.tag == 102 && isAnimate == NO)
    {
        // 右移
        isAnimate = YES;
        
        [UIView animateWithDuration: 0.3  delay: 0.0
                        options: UIViewAnimationOptionCurveEaseOut
                        animations: ^(){
                            roleViews[0].alpha = 1.0;
                            roleViews[5].alpha = 0.0;
                            for (int i = 0; i <= 5; i++)
                                roleViews[i].frame = roleViews[i+1].frame;
                        }
                         completion: ^(BOOL finished){
                             GameDataManager* pManager = [GameDataManager sharedInstance];
                             
                             if (pManager.whoIsSelecting == 1)
                                 [pManager minusHostSelectedRole];
                             else
                                 [pManager minusGuestSelectedRole];
                             
                             [self setAllRoleView];
                             [self resetAllRoleViewFrame];
                             [self setCurrentRoleStatus];
                             
                             isAnimate = NO;
                         }
        ];
        [[AudioManager sharedInstance] PlaySFX:@"SelectSFX"];
    }
    }
}

#pragma mark - reset

- (void)resetAllRoleViewFrame
{    
    for (int i = 0; i <= 6; i++)
    {
        roleViews[i].frame = roleViewsFrame[i];
    }
}

- (void)setAllRoleView
{
    @autoreleasepool 
    {
        GameDataManager* pManager = [GameDataManager sharedInstance];
        int curIndex = 0;
    
        if (pManager.whoIsSelecting == 1)
            curIndex = pManager.hostSelectedRole;
        else 
            curIndex = pManager.guestSelectedRole;
    
        // 绘制lock图像的block
        __weak __block NSDictionary* pDictionary = nil;
        __block int i = 0;
        void (^drawLockBlock)() = ^(){
            // 加锁
            @autoreleasepool {
            NSNumber* thereHold = [pDictionary objectForKey:@"unlock"];
            BOOL isNeedDrawLock = NO;
        
            if (pManager.whoIsSelecting == 1 && pManager.hostWinCount < [thereHold intValue])
                isNeedDrawLock = YES;
            else if (pManager.whoIsSelecting == 2 &&pManager.guestWinCount < [thereHold intValue])
                isNeedDrawLock = YES;
        
            NSNumber* unlockNumber = [pDictionary objectForKey:@"unlock"];
        
            if (isNeedDrawLock == YES)
            {
                if (3 == i)
                    [self drawLockWithView:roleViews[i] unlockScore:[unlockNumber integerValue]];
                else 
                    [self drawLockWithView:roleViews[i] unlockScore:0];
            }
            }

        };
    
        for (i = 3; i <= 6; i++)
        {
            int index = (curIndex + i-3 + 8)%8;
            pDictionary = [NSDictionary dictionaryWithDictionary:[pManager.roles objectAtIndex:index]];
            roleViews[i].image = [UIImage imageNamed:[pDictionary objectForKey:@"win_pic"]];
        
            drawLockBlock();
        }

        for (i = 2; i >=0 ;i--)
        {
            int index = (curIndex-(2-i)+8-1)%8;
            pDictionary = [NSDictionary dictionaryWithDictionary:[pManager.roles objectAtIndex:index]];
        
            roleViews[i].image = [UIImage imageNamed:[pDictionary objectForKey:@"win_pic"]];
        
            drawLockBlock();
        }
    
        roleViews[0].alpha = 0.0;
        roleViews[6].alpha = 0.0;
        roleViews[1].alpha = 1.0;
        roleViews[5].alpha = 1.0;
    }
}

- (void)setCurrentRoleStatus
{
    @autoreleasepool 
    {
        GameDataManager* pManager = [GameDataManager sharedInstance];
        FontManager*     pFont    = [FontManager sharedInstance];
        int currIndex = 0;
    
        if (pManager.whoIsSelecting == 1)
            currIndex = pManager.hostSelectedRole;
        else 
            currIndex = pManager.guestSelectedRole;
    
        // 名字
        __weak NSDictionary* pDictionary = [NSDictionary dictionaryWithDictionary:[pManager.roles objectAtIndex:currIndex]];
        [pFont setFontForView:nameImageView WithSize:17 WithString:[pDictionary objectForKey:@"name"]];
    
        __weak NSMutableArray* selectedSay =  [StringSlicer SliceStr:[pDictionary objectForKey:@"select_say"] subLen:50];
    
        // 1st row
        [pFont setFontForView:firstRowSayImageView WithSize:12 WithString:(NSString*)[selectedSay objectAtIndex:0]];
    
        // 2nd row
        [pFont setFontForView:secondRowSayImageView WithSize:12 WithString:(NSString*)[selectedSay objectAtIndex:1]];
    
    
        // 显示赢的场数
        __autoreleasing NSString* textScore = nil;
        if (pManager.whoIsSelecting == 1)
            textScore = [NSString stringWithFormat:@"%06d", pManager.hostWinCount];
        else
            textScore = [NSString stringWithFormat:@"%06d", pManager.guestWinCount];
    
        winCountText.image = [[[FontManager sharedInstance] fontWithSize12] writeTextToTexture:textScore];
    
        // 显示playIndicator
        if ([[GameDataManager sharedInstance] whoIsSelecting] == 1)
            palyerIndicatorImageView.image = [UIImage imageNamed:@"RolePlayer1.png"];
        else
            palyerIndicatorImageView.image = [UIImage imageNamed:@"RolePlayer2.png"];
    }
}

- (void)drawLockWithView:(UIImageView*)imageView 
             unlockScore:(NSInteger)unlockScore
{
    @autoreleasepool{
        UIImage* lockImage = [UIImage imageNamed:@"RoleLock.png"];    
        NSString* unlockImageName = [NSString stringWithFormat:@"RoleWin%d", unlockScore];
        UIImage* scoreImage = [UIImage imageNamed:unlockImageName];
    
        UIGraphicsBeginImageContext(imageView.image.size);
        [imageView.image drawAtPoint:CGPointMake(0.0, 0.0)];
        [lockImage drawAtPoint:CGPointMake(0.0, 0.0)];
        [scoreImage drawAtPoint:CGPointMake(0.0, 0.0)];
        imageView.image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
}

- (BOOL)isCurrentRoleAvaiable
{
    BOOL isAvaiable = NO;
    @autoreleasepool 
    {
        GameDataManager* pManager = [GameDataManager sharedInstance];
    
        int currentIndex;
        if (pManager.whoIsSelecting == 1)
            currentIndex = [pManager hostSelectedRole];
        else 
            currentIndex = [pManager guestSelectedRole];
    
        __autoreleasing NSDictionary* pDictionary = [NSDictionary dictionaryWithDictionary:[pManager.roles objectAtIndex:currentIndex]];
    
        __autoreleasing NSNumber* thereHold = [pDictionary objectForKey:@"unlock"];
        
    
        if (pManager.whoIsSelecting == 1 && pManager.hostWinCount >= [thereHold intValue])
            isAvaiable = YES;
        else if (pManager.whoIsSelecting == 2 &&pManager.guestWinCount >= [thereHold intValue])
            isAvaiable = YES;
    }
    return isAvaiable;
}

@end
